package addressbook.actions;

import java.io.IOException;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.MissingResourceException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.util.MessageResources;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import addressbook.Constants;
import addressbook.forms.SearchForm;

/**
 * <strong>SearchAction</strong> will take the search parameters
 * specified by the user and create the Sql statement to be used
 * by the appropriate forward.
 */
public final class SearchAction extends AbstActionBase {

	private Log log =
        LogFactory.getLog(this.getClass().getName());

    public ActionForward execute(ActionMapping mapping,
				 ActionForm form,
				 HttpServletRequest request,
				 HttpServletResponse response)
	throws Exception {

		Locale locale = getLocale(request);
		MessageResources messages = getResources(request);

//		ActionMessages errors = new ActionMessages();
		ActionErrors errors = new ActionErrors();
		String name = ((SearchForm) form).getName();
		String phone = ((SearchForm) form).getPhone();
		String address=((SearchForm)form).getAddress();

		if (!errors.isEmpty()) {
		    saveErrors(request, errors);
		    return (new ActionForward(mapping.getInput()));
		}

		String strSql = new String("SELECT * FROM " + Constants.TABLENAME + " WHERE ");

		if (!name.equals(""))
			strSql = strSql + "name LIKE '"+ name +"%' AND";
		if (!phone.equals(""))
			strSql = strSql + " phone LIKE '"+ phone +"%' AND";
		if (!address.equals(""))
			strSql = strSql + " address LIKE '"+ address +"%'";
		else
		    strSql = strSql.substring(0,strSql.length()-3);

	    strSql = strSql + "ORDER by ID";
	    HttpSession session = request.getSession();
	    if (log.isDebugEnabled()) {
			log.debug("SearchAction session = " + session);
			log.debug("SearchAction strSql = " + strSql);

		}


		session.setAttribute(Constants.SQLSTMT_KEY, strSql);

		return (mapping.findForward(Constants.FORWARD_SUCCESS));

    }
}
